package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"net"
)
import pb "demo/micro/grpc/proto"

type helloServer struct{}

func (s *helloServer) SayHello(c context.Context, request *pb.HelloRequest) (*pb.HelloResponse, error) {
	msg := request.Name
	return &pb.HelloResponse{Message: "hello: " + msg}, nil
}

type linfangyiServer struct{}

func (s *linfangyiServer) Hello(ctx context.Context, req *pb.LinfangyiRequest) (*pb.LinfangyiResponse, error) {
	linfangyi := map[string]string{
		"name": "林芳伊",
		"age":  "18",
	}

	question := req.Question
	return &pb.LinfangyiResponse{Resp: linfangyi[question]}, nil
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
func StartServer() {
	listener, err := net.Listen("tcp", ":8972")
	checkErr(err)

	s := grpc.NewServer() //grpc server
	defer s.GracefulStop()

	pb.RegisterGreeterServer(s, &helloServer{}) //注册service
	pb.RegisterLinfangyiServiceServer(s, &linfangyiServer{})

	fmt.Println("register GreeterService")
	fmt.Println("register linfangyiService")

	reflection.Register(s) //在给定的gRPC服务器上注册服务器反射服务

	// Serve方法在lis上接受传入连接，为每个连接创建一个ServerTransport和server的goroutine。
	// 该goroutine读取gRPC请求，然后调用已注册的处理程序来响应它们。
	fmt.Println("start grpc server")
	err = s.Serve(listener)
	checkErr(err)
}
